<template>
      <div>
        <p class="fwbold fs-md mg20">· 服务券兑付</p>
        <el-divider></el-divider>
        <div class="card">
          <div class="menu-box">
            <el-tabs v-model="activeName" @tab-click="tabClick" type="border-card" class="ml30 mr30 mb30">
              <el-tab-pane :label="item.dictLabel" :name="item.dictValue" v-for="(item, index) in couponStatus"
                           :key="index">
                  <div class="tr mb10 mr10">
                      <el-button type="primary" @click="showVerifyDialog" class="mb20">补充签署真实性声明</el-button>
                  </div>
                <el-table 
                  v-loading="tableLoading" 
                  :data="tableTreeData" 
                  style="width: 100%;min-height: 300px;"
                  row-key="subsidyId"
                  :tree-props="{children: 'children'}"
                  default-expand-all>
                  <el-table-column label="订单编号" width="210">
                    <template slot-scope="{ row }">
                      {{ row.subsidyType === 1 ? row.subsidyId : row.orderId || '--' }}
                    </template>
                  </el-table-column>
                  <el-table-column label="服务产品名称" prop="productName" width="180"></el-table-column>
                  <el-table-column label="服务企业" prop="companyName" width="180">
                    <template slot-scope="{ row }">
                      {{  row.companyName ? row.companyName : '--' }}
                    </template>
                  </el-table-column>
                  <el-table-column label="服务完成时间" prop="finishTime" width="160">
                    <template slot-scope="{ row }">
                      {{ row.finishTime ? moment(row.finishTime).format('YYYY-MM-DD HH:mm:ss') : '--' }}
                    </template>
                  </el-table-column>
                  <el-table-column label="合同金额(元)" prop="price">
                    <template slot-scope="{ row }">
                      {{ row.orderType === 2 ? $priceToThousands(row.totalPrice) :  $priceToThousands(row.price) }}
                    </template>
                  </el-table-column>
                  <el-table-column label="拟兑付金额(元)" prop="discountPrice">
                    <template slot-scope="{ row }">
                      {{ $priceToThousands(row.discountPrice) }}
                    </template>
                  </el-table-column>
                  <el-table-column label="实际兑付金额(元)" prop="actualDiscountPrice">
                    <template slot-scope="{ row }">
                      {{ $priceToThousands(row.actualDiscountPrice) }}
                    </template>
                  </el-table-column>
                  <el-table-column label="申请状态">
                    <template slot-scope="scope">
                      <!--                      0-初始，1-申请中，2-审核通过，3-审核拒绝，4-退回修改-->
                      <span v-if="scope.row.status === 0" class="color-warning">待申请</span>
                      <span v-if="scope.row.status === 1 || scope.row.status === 5 || scope.row.status === 10 || scope.row.status === 20" class="color-warning">待审核</span>
                      <span v-if="scope.row.status === 2" class="color-success">审核通过</span>
                      <span v-if="scope.row.status === 4" class="color-red">退回修改</span>
                      <span v-if="scope.row.status === 3" class="color-red">审核不通过</span>
                      <span v-if="scope.row.status === null">--</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="补充附加条款状态" prop="additionalTermStatus" width="130">
                    <!-- 补充附加条款状态：-1 不需要补充 0-待补充 1-已补充 2-已锁定 -->
                    <template slot-scope="scope">
                      <span v-if="scope.row.additionalTermStatus === -1" class="color-success">不需要补充</span>
                      <span v-if="scope.row.additionalTermStatus === 0" class="color-warning">待补充</span>
                      <span v-if="scope.row.additionalTermStatus === 1" class="color-success">已补充</span>
                      <span v-if="scope.row.additionalTermStatus === 2" class="color-success">已锁定</span>
                      <span v-if="scope.row.additionalTermStatus === null">--</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" fixed="right" width="220">
                    <template slot-scope="scope">
                      <el-button v-if="scope.row.status == 0 && !(scope.row.subsidyType == 1 || scope.row.subsidyMerged == 1)" type="text"
                                 @click="handleClick(scope.row, 'apply')">申请兑付
                      </el-button>
                      <el-button v-else-if="scope.row.status == 4" type="text"
                                 @click="handleClick(scope.row, 'edit')">修改
                      </el-button>
                       <el-button v-else-if="scope.row.status != null" type="text" @click="handleClick(scope.row, 'view')">查看</el-button>
                      <el-button 
                        v-if="scope.row.additionalTermStatus === 0 || scope.row.additionalTermStatus === 1" 
                        type="text" 
                        @click="showAdditionalTermDialog(scope.row)">
                        补充附加条款
                      </el-button>
                      <el-button 
                        v-if="scope.row.status !== 0 && scope.row.status !== 2 && scope.row.status !== 3 && scope.row.status !== null && !(scope.row.subsidyType == 1 || scope.row.subsidyMerged == 1)" 
                        type="text" 
                        @click="handleWithdraw(scope.row)">
                        撤回兑付
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-pagination class="pagination_box" @size-change="handleSizeChange"
                               @current-change="handleCurrentChange"
                               :current-page="pageData.currentPage"
                               :page-sizes="[10, 20, 30, 40, 50]"
                               :page-size="pageData.pageSize"
                               layout="total, sizes, prev, pager, next, jumper"
                               :total="pageData.totalPage">
                </el-pagination>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>

        <el-dialog
          title="补充签署真实性声明" 
          top="0px"
          :visible.sync="verifyDialogVisible"
          append-to-body
          :close-on-click-modal="false"
          width="80%">
          <div class="verify-notice">
            <div class="notice-section">
              <h4 class="section-title">兑付真实性要求</h4>
              <div class="declaration-content">
                <p class="declaration-title">签署兑付申请及佐证材料真实性声明：</p>
                <p class="declaration-text">
                  为保障服务券兑付结算工作顺利进行，根据2025年第一次兑付申请专家评审会提出的相关意见，请所有提交兑付申请的服务商补充提供真实性声明（在查看后刷脸加盖电子签章），确保所提供的合同及佐证材料准确、真实、合法，服务商对所提交的申请承担有关法律责任。
                </p>
              </div>
            </div>
            <div class="notice-section">
              <h4 class="section-title">操作说明</h4>
              <ol class="operation-steps">
                <li>请逐一点击查看真实性承诺书，当签署状态变成"已查看"时，可以勾选订单前的方块，建议多条选择，然后点击"签署真实性声明"，进行扫码签署，签署成功后请点击"完成签署",点击完成签署后，签署状态变为"已签署"才算部署完成。</li>
              </ol>
            </div>
          </div>
          
          <el-table
            v-loading="verifyTableLoading"
            :data="verifyTableData"
            max-height="550"
            empty-text="暂无补充真实性说明订单"
            @selection-change="handleSelectionChange">
            <el-table-column
              type="selection"
              width="55"
              :selectable="row => row.confirmationStatus === 1">
            </el-table-column>
            <el-table-column label="兑付申请编号" prop="subsidyId" width="180"></el-table-column>
            <el-table-column label="订单编号" prop="orderId" width="180"></el-table-column>
            <el-table-column label="签署状态" width="100">
              <template slot-scope="{ row }">
                <span :class="getStatusClass(row.confirmationStatus)">
                  {{ getStatusText(row.confirmationStatus) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="服务商名" prop="serviceName" width="180"></el-table-column>
            <el-table-column label="买方企业名" prop="companyName" width="180"></el-table-column>
            <el-table-column label="服务产品名" prop="productName" width="180"></el-table-column>
            <el-table-column label="完成时间" prop="finishTime" width="180">
              <template slot-scope="{ row }">
                {{ moment(row.finishTime).format('YYYY-MM-DD HH:mm:ss') }}
              </template>
            </el-table-column>
            <el-table-column label="补贴金额(元)" prop="discountPrice" width="120">
              <template slot-scope="{ row }">
                {{ $priceToThousands(row.discountPrice) }}
              </template>
            </el-table-column>
            <el-table-column label="合同金额(元)" prop="price" width="120">
              <template slot-scope="{ row }">
                {{ $priceToThousands(row.price) }}
              </template>
            </el-table-column>
            <el-table-column label="原始金额(元)" prop="totalPrice" width="120">
              <template slot-scope="{ row }">
                {{ $priceToThousands(row.totalPrice) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="180">
              <template slot-scope="scope">
                <el-button 
                  type="text" 
                  @click="viewVerifyDoc(scope.row)">
                  查看真实性承诺书
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            class="pagination_box"
            @size-change="handleVerifyPageSizeChange"
            @current-change="handleVerifyPageChange"
            :current-page="verifyPageData.currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="verifyPageData.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="verifyPageData.totalPage">
          </el-pagination>

          <div slot="footer" class="tc">
            <el-button @click="verifyDialogVisible = false">取 消</el-button>
            <el-button 
              type="primary" 
              @click="handleSign"
              :disabled="selectedRows.length === 0">
              签署真实性声明
            </el-button>
          </div>
        </el-dialog>

        <el-dialog
          title="扫码签署"
          :visible.sync="qrCodeDialogVisible"
          width="450px"
          center
          append-to-body>
          <div class="qr-code-container">
            <p class="qr-code-tip">请使用手机扫描二维码打开页面，请经办人完成刷脸签署。</p>
            <qrcode-vue :value="qrCodeUrl" :size="200"></qrcode-vue>
            <el-button type="primary" @click="confirmSigned" class="mt20">完成签署</el-button>
          </div>
        </el-dialog>

        <!-- 补充附加条款弹窗 -->
        <el-dialog
          title="补充附加条款"
          :visible.sync="additionalTermVisible"
          :close-on-click-modal="false"
          width="600px">
          <el-form>
            <el-form-item label="附加条款内容">
              <el-input
                v-model="additionalTermContent"
                type="textarea"
                :rows="6"
                :maxlength="10000"
                show-word-limit
                placeholder="请输入附加条款内容">
              </el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="additionalTermVisible = false">取 消</el-button>
            <el-button type="primary" :loading="submitLoading" @click="submitAdditionalTerm">确 定</el-button>
          </span>
        </el-dialog>
      </div>
</template>
<script>
import {getSubsidyPage,confirmationFileDownload,signConfirmationLink,getadditionalTerm,editAdditionalTerm,withdrawSubsidy} from "@/api/homeApi";
import moment from 'moment';
import QrcodeVue from 'qrcode-vue'

export default {
  data() {
    return {
      moment,
      // couponStatus: [{dictLabel: '全部', dictValue: '-1'}],
      activeName: "-1",
      // state: 0待申请、1待审核、2审核通过、3退回修改、4审核不通过
      tableData: [
      ],
      couponStatus: [
        {dictLabel: '全部', dictValue: 'all'},
        {dictLabel: '待申请', dictValue: '0'},
        {dictLabel: '待审核', dictValue: '1'},
        {dictLabel: '审核通过', dictValue: '2'},
        {dictLabel: '退回修改', dictValue: '4'},
        {dictLabel: '审核不通过', dictValue: '3'}
      ],
      tableLoading: false,
      pageData: {
        currentPage: 1,
        pageSize: 50,
        totalPage: 0
      },
      currentIndex: 0,
      verifyDialogVisible: false,
      verifyTableLoading: false,
      verifyTableData: [],
      verifyRequirements: '这里是兑付真实性要求说明文字...',
      selectedRows: [],
      showQRCode: false,
      qrCodeUrl: '',
      verifyPageData: {
        currentPage: 1,
        pageSize: 10,
        totalPage: 0
      },
      qrCodeDialogVisible: false,
      additionalTermVisible: false,
      additionalTermContent: '',
      currentRow: null,
      submitLoading: false
    };
  },
  computed: {
    commonDict() {
      return this.$store.state.common.commonDict;
    },
    tableTreeData() {
      // 递归处理数据，将subOrders转换为children
      const processTreeData = (data) => {
        return data.map(item => {
          const newItem = {...item};
          if (newItem.subOrders && newItem.subOrders.length > 0) {
            newItem.children = processTreeData(newItem.subOrders);
            delete newItem.subOrders;
          }
          return newItem;
        });
      };
      
      return processTreeData(this.tableData);
    }
  },
  components: {
    QrcodeVue
  },
  async mounted() {
    if (this.commonDict.length === 0) {
      await this.$store.dispatch("getCommonDict")
    }
    this.activeName = this.couponStatus[0].dictValue
    // 获取可兑付产品列表
    this.getSubsidyList()
  },
  methods: {
    getSubsidyList() {
      this.tableLoading = true
      let data = {
        pageNo: this.pageData.currentPage,
        pageNum: this.pageData.pageSize,
        status: this.activeName
      }
      if (this.activeName == 'all') {
        delete data['status']
      }
      getSubsidyPage(data).then(res => {
        if (res.code === 200) {
          // 直接使用原始数据，让计算属性处理树形结构
          this.tableData = [...res.rows]
          this.$set(this.pageData, 'totalPage', res.total)
        }
      }).finally(() => {
        this.tableLoading = false
      })
    },
    tabClick(val) {
      this.currentIndex = val.index
      this.getSubsidyList()
    },
    handleSizeChange(val) {
      this.$set(this.pageData, 'pageSize', val)
      this.getSubsidyList()
    },
    handleCurrentChange(val) {
      this.$set(this.pageData, 'currentPage', val)
      this.getSubsidyList()
    },
    handleClick(row, type) {
      this.$router.push({
        name: "服务商申请兑付",
        query: {
          orderId: row.orderId,
          subsidyId: row.subsidyId,
          subsidyType: row.subsidyType,
          type
        }
      })
    },
    showVerifyDialog() {
      this.verifyDialogVisible = true
      this.getVerifyOrderList()
    },
    async getVerifyOrderList(confirmationStatus='') {
      this.verifyTableLoading = true
      try {
        let data = {
          pageNo: this.verifyPageData.currentPage,
          pageNum: this.verifyPageData.pageSize,
          confirmationStatus: confirmationStatus
        }
        const res = await getSubsidyPage(data)
        if (res.code === 200) {
          this.verifyTableData = [...res.rows]
          this.$set(this.verifyPageData, 'totalPage', res.total)
        }
      } catch (error) {
        this.$message.error('获取列表失败')
      } finally {
        this.verifyTableLoading = false
      }
    },
    async viewVerifyDoc(row) {
      try {
        const res = await confirmationFileDownload({subsidyId: row.subsidyId})
        if (res.code === 200) {
          // 处理查看文档逻辑
          const url = process.env.VUE_APP_BASE_API+`/public/file/v1/temp/get?token=${res.data?.token}`
          window.open(url)
          // 等待一小段时间后刷新列表
          setTimeout(() => {
            this.getVerifyOrderList()
          }, 1000)
        }
      } catch (error) {
        this.$message.error('获取文档失败')
      }
    },
    handleSelectionChange(rows) {
      this.selectedRows = rows
    },
    async handleSign() {
      try {
        const subsidyIds = this.selectedRows.map(row => row.subsidyId)
        const res = await signConfirmationLink({subsidyIds: subsidyIds})
        if (res.code === 200) {
          this.qrCodeUrl = res.data 
          this.qrCodeDialogVisible = true
        }
      } catch (error) {
        this.$message.error('获取签署链接失败')
      }
    },
    confirmSigned() {
      this.qrCodeDialogVisible = false
      this.getVerifyOrderList()
    },
    handleVerifyPageSizeChange(val) {
      this.$set(this.verifyPageData, 'pageSize', val)
      this.getVerifyOrderList()
    },
    handleVerifyPageChange(val) {
      this.$set(this.verifyPageData, 'currentPage', val)
      this.getVerifyOrderList()
    },
    getStatusText(status) {
      const statusMap = {
        0: '未操作',
        1: '已查看',
        2: '已签署'
      }
      return statusMap[status] || '未知状态'
    },
    getStatusClass(status) {
      const classMap = {
        0: 'color-info',
        1: 'color-warning',
        2: 'color-success'
      }
      return classMap[status] || ''
    },
    // 显示附加条款弹窗
    async showAdditionalTermDialog(row) {
      this.currentRow = row
      this.additionalTermVisible = true
      try {
        const res = await getadditionalTerm({ 
          subsidyId: row.subsidyId // 根据实际参数调整
        })
        this.additionalTermContent = res.data.additionalTerm || ''
      } catch (error) {
        this.$message.error('获取附加条款失败')
      }
    },

    // 提交附加条款
    async submitAdditionalTerm() {
      if (!this.additionalTermContent.trim()) {
        this.$message.warning('请输入附加条款内容')
        return
      }

      this.submitLoading = true
      try {
        await editAdditionalTerm({
          subsidyId: this.currentRow.subsidyId, // 根据实际参数调整
          additionalTerm: this.additionalTermContent
        })
        this.$message.success('提交成功')
        this.additionalTermVisible = false
        this.getSubsidyList() // 刷新表格数据
      } catch (error) {
        this.$message.error('提交失败')
      } finally {
        this.submitLoading = false
      }
    },
    async handleWithdraw(row) {
      this.$confirm('确定要撤回该兑付申请吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        withdrawSubsidy({
          subsidyId: row.subsidyId // 假设这是接口需要的参数，实际参数可能有所不同
        }).then(res => {
          if (res.code === 200) {
            this.$message.success('撤回成功')
            this.getSubsidyList()
          } else {
            this.$message.error(res.msg || '撤回失败')
          }
        }).catch(err => {
          this.$message.error('操作失败：' + err.message)
        })
      }).catch(() => {
        // 用户取消操作
      })
    },
  },
};
</script>

<style scoped>
/*修改elementiUI菜单底部边框的颜色*/
:deep .el-menu--horizontal > .el-menu-item.is-active {
  border-bottom-color: #d32521;
}

:deep .el-table thead {
  color: #000;
}

.pagination_box {
  text-align: right;
  margin-top: 6px;
}

.verify-notice {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.notice-section {
  margin-bottom: 20px;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 12px;
  padding-left: 10px;
  border-left: 4px solid #409EFF;
}

.declaration-content {
  padding: 0 10px;
}

.declaration-title {
  color: #303133;
  font-weight: 500;
  margin-bottom: 8px;
}

.declaration-text {
  color: #606266;
  line-height: 1.6;
  text-align: justify;
}

.operation-steps {
  padding-left: 30px;
  margin: 0;
  
  li {
    color: #606266;
    line-height: 1.8;
    margin-bottom: 8px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
}

.qr-code-container {
  text-align: center;
  padding: 20px 0;
}

.qr-code-tip {
  font-size: 14px;
  color: #606266;
  margin-bottom: 20px;
}

.mt20 {
  margin-top: 20px;
}

.color-info {
  color: #909399;
}

.color-warning {
  color: #E6A23C;
}

.color-success {
  color: #67C23A;
}
</style>
